const CACHE_KEY = 'house-interest-analysis-input-cache'

const vm = new Vue({
    el: 'main',
    data: {
        host: window.location.origin,
        interestAscend: true,
        downPaymentRateInput: '0',
        downPaymentRate: 0,
        yearlyInterestRateFromInput: '0',
        yearlyInterestRateFrom: 0,
        yearlyInterestRateToInput: '0',
        yearlyInterestRateTo: 0,
        deltaInput: '0',
        delta: 0,
        payMonthInput: '0',
        payMonth: 0,
        totalAmountInput: '0',
        totalAmount: 0,
        results: [],
        errMsg: '',
    },
    created: function() {
    },
    mounted: function() {
        let inputCache = localStorage.getItem(CACHE_KEY)
        inputCache = JSON.parse(inputCache)
        if (null !== inputCache) {
            this.downPaymentRateInput = inputCache.downPaymentRateInput
            this.downPaymentRate = inputCache.downPaymentRateInput / 100
            this.yearlyInterestRateFromInput = inputCache.yearlyInterestRateFromInput
            this.yearlyInterestRateFrom = inputCache.yearlyInterestRateFromInput / 100
            this.yearlyInterestRateToInput = inputCache.yearlyInterestRateToInput
            this.yearlyInterestRateTo = inputCache.yearlyInterestRateToInput / 100
            this.deltaInput = inputCache.deltaInput
            this.delta = inputCache.deltaInput / 100
            this.payMonthInput = inputCache.payMonthInput
            this.payMonth = inputCache.payMonthInput
            this.totalAmountInput = inputCache.totalAmountInput
            this.totalAmount = inputCache.totalAmountInput
        }
    },
    watch: {
        downPaymentRateInput: function(val) {
            if (null === val || undefined === val) {
                this.errMsg = '请输入首付百分比'
                return
            }
            val = parseFloat(val)
            if (val < 0 || val > 100) {
                this.errMsg = '首付百分比范围应在0%~100%'
                return
            }
            this.errMsg = ''
            this.downPaymentRate = val / 100
            this.refreshCache()
        },
        yearlyInterestRateFromInput: function(val) {
            if (null === val || undefined === val) {
                this.errMsg = '请输入贷款年利率下限'
                return
            }
            val = parseFloat(val)
            if (val < 1 || val > 100) {
                this.errMsg = '贷款年利率下限范围应在1%~100%'
                return
            }
            this.errMsg = ''
            this.yearlyInterestRateFrom = val / 100
            this.refreshCache()
        },
        yearlyInterestRateToInput: function(val) {
            if (null === val || undefined === val) {
                this.errMsg = '请输入贷款年利率上限'
                return
            }
            val = parseFloat(val)
            if (val < 1 || val > 100) {
                this.errMsg = '贷款年利率上限范围应在1%~100%'
                return
            }
            if (val === 0) {
                this.errMsg = '请先输入利率上限'
                return
            }
            if (this.yearlyInterestRateTo >= val) {
                this.errMsg = '利率上限应大于利率下限'
                return
            }
            this.errMsg = ''
            this.yearlyInterestRateTo = val / 100
            this.refreshCache()
        },
        deltaInput: function (val) {
            if (null === val || undefined === val) {
                return
            }
            val = parseFloat(val)
            if (val < 0 || val > 1) {
                this.errMsg = '贷款年利率变化速率范围应在(0%, 1%)'
                return
            }
            this.errMsg = ''
            this.delta = val / 100
            this.refreshCache()
        },
        payMonthInput: function (val) {
            if (null === val || undefined === val) {
                return
            }
            val = parseInt(val)
            if (val < 0 || val > 720) {
                this.errMsg = '还款月数范围应在1~720'
                return
            }
            this.errMsg = ''
            this.payMonth = val
            this.refreshCache()
        },
        totalAmountInput: function (val) {
            if (null === val || undefined === val) {
                return
            }
            val = parseFloat(val)
            if (val < 0) {
                this.errMsg = '房屋总价范围应为正数'
                return
            }
            this.errMsg = ''
            this.totalAmount = val
            this.refreshCache()
        },
    },
    methods: {
        submit: function () {
            this.validate()
            if (this.errMsg.length > 0) {
                alert('请先处理好问题再进行分析')
                return
            }
            this.results = []
            let yearlyInterestRate = this.yearlyInterestRateFrom
            let id = 0
            while (yearlyInterestRate.toFixed(10) <= this.yearlyInterestRateTo.toFixed(10)) {
                ++id
                let loan = this.totalAmount * (1 - this.downPaymentRate)
                let downPayment = this.totalAmount - loan
                let monthlyInterestRate = yearlyInterestRate / 12
                let monthlyPayAmount = this.pmt(monthlyInterestRate, loan, this.payMonth)
                let totalPayment = monthlyPayAmount * this.payMonth
                let total = downPayment + totalPayment
                let result = {
                    id,
                    yearlyInterestRate: (yearlyInterestRate * 100).toFixed(2),
                    monthlyInterestRate: monthlyInterestRate * 100,
                    downPayment: this.toThousands(downPayment.toFixed(2)),
                    loan: this.toThousands(loan.toFixed(2)),
                    monthlyPayAmount: this.toThousands(monthlyPayAmount.toFixed(2)),
                    totalPayment: this.toThousands(totalPayment.toFixed(2)),
                    totalInterest: this.toThousands((totalPayment - loan).toFixed(2)),
                    total: this.toThousands(total.toFixed(2))
                }
                this.results.push(result)
                yearlyInterestRate += this.delta
            }
            this.interestAscend = true
            // console.log(JSON.stringify(this.results))
        },
        switchInterestRateSort: function() {
            this.interestAscend = !this.interestAscend
            this.results.sort((v1, v2) => {
                if (this.interestAscend) {
                    return v1.yearlyInterestRate - v2.yearlyInterestRate
                } else {
                    return v2.yearlyInterestRate - v1.yearlyInterestRate
                }
            })
        },
        toThousands: function (num = 0) {
            let result = '';
            let numArr = num.toString().split('.');
            let int = numArr[0];
            let decmial = numArr[1] ? '.' + numArr[1] : '';
            while (int.length > 3) {
               result = ',' + int.slice(-3) + result;
               int = int.slice(0, int.length - 3);
            }
            if (int) {
               result = int + result;
            }
            return result + decmial;
        },
        refreshCache: function () {
            let inputCache = {
                downPaymentRateInput: this.downPaymentRateInput,
                yearlyInterestRateFromInput: this.yearlyInterestRateFromInput,
                yearlyInterestRateToInput: this.yearlyInterestRateToInput,
                deltaInput: this.deltaInput,
                payMonthInput: this.payMonthInput,
                totalAmountInput: this.totalAmountInput,
            }
            localStorage.setItem(CACHE_KEY, JSON.stringify(inputCache))
        },
        pmt: function (monthlyInterestRate, loan, payMonth) {
            let rp1 = 1 + monthlyInterestRate
            let r1 = 1
            for (let i = 0; i < payMonth; ++i) {
                r1 = r1 * rp1
            }
            return loan * monthlyInterestRate * r1 / (r1 - 1)
        },
        validate: function () {
            if (this.downPaymentRate === 0) {
                this.errMsg = '请输入首付百分比'
                return
            }
            if (this.yearlyInterestRateFrom === 0) {
                this.errMsg = '请输入贷款年利率下限'
                return
            }
            if (this.yearlyInterestRateTo === 0) {
                this.errMsg = '请输入贷款年利率上限'
                return
            }
            if (this.delta === 0) {
                this.errMsg = '请输入贷款年利率变化速度'
                return
            }
            if (this.payMonth === 0) {
                this.errMsg = '请输入贷款偿还月数'
                return
            }
            if (this.totalAmount === 0) {
                this.errMsg = '请输入房价总额'
                return
            }
        },
    },
})
